//
//  OtherClientVC.m
//  Marketing
//
//  Created by HanenDev on 16/5/28.
//  Copyright © 2016年 Hanen 3G 01. All rights reserved.
//

#import "OtherClientVC.h"
#import "MyClientCell.h"
#import "NewVisitViewController.h"
#import "SatusSelectViewController.h"
#import "JudgeNumber.h"
#import "VisitDetailViewController.h"
#import "ManagerNoticeBtnView.h"
#import "VisitHistoryCell.h"
#import "MyTextView.h"
#import "AddPersonController.h"
#import "ContactModel.h"
#import "NewContactView.h"
#import "SetButton.h"
#import "ImageButton.h"
#import "MJRefresh.h"
#import "OtherClientVC.h"

#define STARTX [UIView getWidth:10]
#define InfoCellH 44.0f //每格的高度
#define TitileW 80.0f //每个标题label的宽度

#import "MapClientViewController.h"
@interface OtherClientVC ()<UITableViewDataSource,UITableViewDelegate,UITextFieldDelegate,ManagerNoticeBtnViewDelegate>
{
    NSArray    *_detailArray;
    NSArray    *_contactArr;
    NSArray    *_otherArr;
    
    ManagerNoticeBtnView * _topView;
    UIView *firstView;
    UIView *secondView;
    UIView *thirdView;
    UIView *contactView;
    
    CGRect  ContactFrame;
    UIView *addVie;//添加联系人按钮
    
    ImageButton  *_locationBtn;
    UIButton *btnSave;
    
    CLLocationCoordinate2D coordinate;
    
    NSDictionary  *detailDict;
    int pageNum;
}


@property(nonatomic,strong)NSMutableArray    *visitArray;
/**
 *  客户详情
 */
@property(nonatomic,strong)UIView            *detailView;
@property(nonatomic,strong)UIScrollView      *scrollView;
/**
 *  历史拜访
 */
@property(nonatomic,strong)UIView            *visitView;
@property(nonatomic,strong)UITableView       *visitTableView;

@property(nonatomic,strong)UITextField    *companyTF,*levelTF,*fromTF,*statusTF,*addressTF;

@property(nonatomic,strong)UITextField    *principalTF,*personTF,*creTimeTF,*lastTimeTF;//负责人、创建人、创建时间、结束时间

@property(nonatomic,strong)ImageButton       *levelBtn,*formBtn,*statusBtn;

@end

@implementation OtherClientVC

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = graySectionColor;
    self.navigationItem.hidesBackButton = YES;
    
    self.navigationItem.titleView = [ViewTool getNavigitionTitleLabel:self.titleStr];
    
    _topView = [[ManagerNoticeBtnView alloc] initWithFrame:CGRectMake(0, 0, KSCreenW , 35.0f)];
    _topView.backgroundColor = NavBackColor;
    _topView.btnTitleArray =@[@"客户详情",@"历史拜访"];
    _topView.delegate = self;
    [self.view addSubview:_topView];
    
    
    self.navigationItem.leftBarButtonItem=[ViewTool getBarButtonItemWithTarget:self WithAction:@selector(goToBack)];
    
    [self createDetailView];
    [self createVisitView];
    [self initData];
    
    _visitArray = [[NSMutableArray alloc]initWithCapacity:0];
}

- (void)changeNoticeViewWithTitle:(NSString *)btnTitle
{
    if ([btnTitle isEqualToString:@"客户详情"]) {
        //        self.navigationItem.titleView = [ViewTool getNavigitionTitleLabel:self.titleStr];
        
        self.navigationItem.rightBarButtonItem = nil;
        
        _detailView.hidden = NO;
        _visitView.hidden = YES;
        
    }else if([btnTitle isEqualToString:@"历史拜访"]){
        
        //        self.navigationItem.titleView = [ViewTool getNavigitionTitleLabel:@"拜访历史"];
        
        _detailView.hidden = YES;
        _visitView.hidden = NO;
        _visitTableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
            [self loadNewData];
        }];
        [_visitTableView.mj_header beginRefreshing];
        
        // 上拉刷新
        _visitTableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [self loadMoreData];
            });
        }];
    }
}
#pragma mark -------客户详情界面
- (void)createDetailView{
    
    _detailArray = @[@"公司",@"地址",@"级别",@"来源",@"状态"];
    _contactArr = @[@"姓名",@"职务",@"电话",@"邮箱",@"备注"];
    _otherArr = @[@"负责人",@"创建人",@"创建时间",@"结束时间"];
    
    _detailView = [[UIView alloc]initWithFrame:CGRectMake(0, _topView.maxY, KSCreenW, KSCreenH - 64 - _topView.height)];
    [self.view addSubview:_detailView];
    
    _scrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 0, KSCreenW, KSCreenH - _topView.height)];
    _scrollView.showsVerticalScrollIndicator=NO;
    [_detailView addSubview:_scrollView];
    _scrollView.backgroundColor = graySectionColor;
    [self createUI];
    
}
- (void)createUI{
    
    CGFloat tfH    = InfoCellH;
    CGFloat tfW    = KSCreenW - 2*STARTX  - 80.0f;
    
    firstView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, KSCreenW, 120.0f)];
    [_scrollView addSubview:firstView];
    firstView.backgroundColor = [UIColor whiteColor];
    
    UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, KSCreenW, 40)];
    view.backgroundColor = graySectionColor;
    [firstView addSubview:view];
    
    UIImageView *imageView1 = [[UIImageView alloc]initWithFrame:CGRectMake(STARTX, 8, 5, view.height - 16)];
    [view addSubview:imageView1];
    
    UILabel *basicLabel = [[UILabel alloc]initWithFrame:CGRectMake(STARTX, view.height - 20, 200, 20)];
    basicLabel.text = @"客户信息";
    [ViewTool setLableFont12:basicLabel];
    basicLabel.textColor = blackFontColor;
    [view addSubview:basicLabel];
    
    UIView *lineView = [[UIView alloc]initWithFrame:CGRectMake(0, view.height - 1, KSCreenW , 1)];
    lineView.backgroundColor = grayLineColor;
    [view addSubview:lineView];
    
    for (int i = 0; i<_detailArray.count; i++) {
        UILabel *label = [ViewTool getLabelWith:CGRectMake(STARTX, view.maxY + (InfoCellH * i), 80.0f, InfoCellH) WithTitle:_detailArray[i] WithFontSize:16.0f WithTitleColor:grayFontColor WithTextAlignment:NSTextAlignmentLeft];
        [ViewTool setLableFont13:label];
        [firstView addSubview:label];
        
        if (i != _detailArray.count - 1) {
            UIView *line = [ViewTool getLineViewWith:CGRectMake(STARTX, view.maxY +InfoCellH*(i+1) -1 , KSCreenW - STARTX, 1) withBackgroudColor:grayLineColor];
            [firstView addSubview:line];
        }else{
            UIView *line = [ViewTool getLineViewWith:CGRectMake(0, view.maxY +InfoCellH*(i+1) -1 , KSCreenW, 1) withBackgroudColor:grayLineColor];
            [firstView addSubview:line];
        }
        
    }
    
    _companyTF = [self addTextFieldWithFrame:CGRectMake(STARTX + 80.0f, view.maxY , tfW, tfH) AndStr:@"" WithTrue:NO];
    [firstView addSubview:_companyTF];
    
    
    _addressTF = [self addTextFieldWithFrame:CGRectMake(_companyTF.x, _companyTF.maxY , tfW, tfH)  AndStr:@"" WithTrue:NO];
    [firstView addSubview:_addressTF];
    
    
    _levelTF = [self addTextFieldWithFrame:CGRectMake(_companyTF.x, _addressTF.maxY , tfW - 30, tfH) AndStr:@"" WithTrue:NO];
    [firstView addSubview:_levelTF];
    
    _fromTF = [self addTextFieldWithFrame:CGRectMake(_companyTF.x, _levelTF.maxY , tfW -30, tfH) AndStr:@"" WithTrue:NO];
    [firstView addSubview:_fromTF];
    
    _statusTF = [self addTextFieldWithFrame:CGRectMake(_companyTF.x, _fromTF.maxY, tfW - 30, tfH) AndStr:@"" WithTrue:NO];
    [firstView addSubview:_statusTF];
    
    firstView.frame = CGRectMake(0, 0, KSCreenW, _statusTF.maxY);
    
    [self initUI];
    
}

- (void)initUI{
    
    secondView = [[UIView alloc]initWithFrame:CGRectMake(0, firstView.maxY , KSCreenW, 120.0f)];
    secondView.backgroundColor = [UIColor whiteColor];
    [_scrollView addSubview:secondView];
    
    
    NewContactView  *newContact1 = [[NewContactView alloc] initWithFrame:CGRectMake(0, 0, KSCreenW, [UIView getWidth:120.0f])];
    ContactFrame = newContact1.frame;
    [secondView addSubview:newContact1];
    
    
    addVie = [ViewTool getLineViewWith:CGRectMake(0, newContact1.maxY, KSCreenW, 0) withBackgroudColor:[UIColor whiteColor]];
    [secondView addSubview:addVie];
    
    UIView *viewLine = [ViewTool getLineViewWith:CGRectMake(0, 0, KSCreenW, 17.0f) withBackgroudColor:graySectionColor];
    [addVie addSubview:viewLine];
    
    UIView *l2 = [ViewTool getLineViewWith:CGRectMake(0, viewLine.height - 1, KSCreenW, 1) withBackgroudColor:grayLineColor];
    [viewLine addSubview:l2];
    
    UIView *l3 = [ViewTool getLineViewWith:CGRectMake(0, addVie.height - 1, KSCreenW, 1) withBackgroudColor:grayLineColor];
    [viewLine addSubview:l3];
    
    secondView.frame = CGRectMake(0, firstView.maxY, KSCreenW, addVie.maxY);
    
    [self initViews];
    
}

- (void)initViews{
    CGFloat labelH = InfoCellH;
    CGFloat tfH    = InfoCellH;
    CGFloat tfW    = KSCreenW-2*STARTX - 80.0f;
    
    thirdView = [[UIView alloc]initWithFrame:CGRectMake(0, secondView.maxY, KSCreenW, 100.0f)];
    
    thirdView.backgroundColor = [UIColor whiteColor];
    [_scrollView addSubview:thirdView];
    
    UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, KSCreenW, 40.0f)];
    view.backgroundColor = graySectionColor;
    [thirdView addSubview:view];
    
    UIView *view1 = [[UIView alloc]initWithFrame:CGRectMake(0, 0, KSCreenW, 1.0f)];
    view.backgroundColor = graySectionColor;
    [view addSubview:view1];
    
    UIImageView *imageView1 = [[UIImageView alloc]initWithFrame:CGRectMake(STARTX, 8, 5, view.height - 16)];
    [view addSubview:imageView1];
    
    UILabel *basicLabel = [[UILabel alloc]initWithFrame:CGRectMake(STARTX, view.height - 20, 200, 20)];
    basicLabel.text = @"其他";
    [ViewTool setLableFont12:basicLabel];
    
    basicLabel.textColor = blackFontColor;
    [view addSubview:basicLabel];
    
    UIView *lineView = [[UIView alloc]initWithFrame:CGRectMake(0, view.height - 1, KSCreenW , 1)];
    lineView.backgroundColor = grayLineColor;
    [view addSubview:lineView];
    
    for (int i = 0; i<_otherArr.count; i++) {
        UILabel *label = [ViewTool getLabelWith:CGRectMake(STARTX, view.maxY + InfoCellH * i, KSCreenW, labelH) WithTitle:_otherArr[i] WithFontSize:16.0f WithTitleColor:grayFontColor WithTextAlignment:NSTextAlignmentLeft];
        [ViewTool setLableFont13:label];
        [thirdView addSubview:label];
        
        UIView *line = [ViewTool getLineViewWith:CGRectMake(STARTX, view.maxY +InfoCellH*(i+1) -1, KSCreenW - STARTX, 1) withBackgroudColor:grayLineColor];
        [thirdView addSubview:line];
        if (i == _otherArr.count - 1) {
            line.frame = CGRectMake(0, view.maxY +InfoCellH*(i+1) -1, KSCreenW, 1);
        }
    }
    
    _principalTF = [self addTextFieldWithFrame:CGRectMake(STARTX + TitileW, view.maxY, tfW, tfH) AndStr:@"请填写负责人" WithTrue:NO];
    [thirdView addSubview:_principalTF];
    
    _personTF = [self addTextFieldWithFrame:CGRectMake(STARTX + TitileW, _principalTF.maxY , _principalTF.width, tfH) AndStr:@"请填写创建人" WithTrue:NO];
    [thirdView addSubview:_personTF];
    
    _creTimeTF = [self addTextFieldWithFrame:CGRectMake(STARTX + TitileW, _personTF.maxY , _principalTF.width, tfH) AndStr:@"请填写创建时间" WithTrue:NO];
    [thirdView addSubview:_creTimeTF];
    
    _lastTimeTF = [self addTextFieldWithFrame:CGRectMake(STARTX + TitileW, _creTimeTF.maxY , _principalTF.width, tfH) AndStr:@"请填写最后修改时间" WithTrue:NO];
    [thirdView addSubview:_lastTimeTF];
    thirdView.frame = CGRectMake(0, secondView.maxY, KSCreenW, _lastTimeTF.maxY);
    
    [_scrollView setContentSize:CGSizeMake(KSCreenW, thirdView.maxY + 2 + 64)];
    
}
#pragma mark
#pragma mark-------tableView
- (void)createVisitView{
    _visitView = [[UIView alloc]initWithFrame:CGRectMake(0, _topView.maxY, KSCreenW, KSCreenH - 64 - _topView.height)];
    _visitView.hidden = YES;
    [self.view addSubview:_visitView];
    
    _visitTableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0,KSCreenW, _visitView.height) style:UITableViewStylePlain];
    _visitTableView.delegate = self;
    _visitTableView.dataSource = self;
    _visitTableView.backgroundColor = graySectionColor;
    _visitTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [_visitView addSubview:_visitTableView];
    
}
- (void)loadNewData{
    pageNum = 1;
    [_visitArray removeAllObjects];
    [self requestHistoryData];
    
}
- (void)loadMoreData{
    pageNum ++;
    [self requestHistoryData];
}


#pragma mark
#pragma mark-----tableView的协议方法

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    return [VisitHistoryCell cellHeight];
    
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return _visitArray.count;
    
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    VisitHistoryCell *cell = [VisitHistoryCell cellWithTableView:tableView WithIndex:indexPath.row];
    if (_visitArray.count >0) {
        ClientModel *client = _visitArray[indexPath.row];
        if (indexPath.row == _visitArray.count -1) {
            cell.lineView.frame = CGRectMake(0, [VisitHistoryCell cellHeight] - 1, KSCreenW, 1);
        }else{
            cell.lineView.frame = CGRectMake(cell.companyLabel.x, [VisitHistoryCell cellHeight] - 1, KSCreenW, 1);
        }
        cell.model = client;
    }
    
    return cell;
    
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}
- (void)goToBack{
    
    [self.navigationController popViewControllerAnimated:YES];
}
- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    self.tabBarController.hidesBottomBarWhenPushed = NO;
}
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    self.tabBarController.hidesBottomBarWhenPushed = YES;
}

-(UITextField *)addTextFieldWithFrame:(CGRect)frame AndStr:(NSString *)placeholder WithTrue:(BOOL)ture
{
    UITextField *textF=[[UITextField alloc]initWithFrame:frame];
    textF.userInteractionEnabled = ture;
    textF.textColor = blackFontColor;
    textF.placeholder=placeholder;
    textF.delegate = self;
    [textF setValue:placeholderGrayFontColor forKeyPath:@"_placeholderLabel.textColor"];
    [ViewTool setTFPlaceholderFont14:textF];
    return textF;
}

#pragma mark--------- 下属客户详情
- (void)initData{
    NSNumber *cidNum =[NSNumber numberWithInt:_cID];
    NSNumber *cidNum1 =[NSNumber numberWithInt:_cUID];
    
    NSDictionary * dic =@{@"token":TOKEN,@"uid":@(UID),@"cid":cidNum ,@"cuid":cidNum1};
    [DataTool postWithUrl:OTHER_DETAIL_CLIENT_URL parameters:dic success:^(id data) {
        NSDictionary *jsonDic = [DataTool changeType:[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil]];
        NSLog(@"%@++++++客户详情",jsonDic);
        id json = [DataTool changeType:jsonDic];
        NSArray *clientArray = json[@"contactsList"];
        
        if (clientArray.count > 0) {
            for (UIView *v in secondView.subviews) {
                if ([v isKindOfClass:[NewContactView class]]) {
                    [v removeFromSuperview];
                }
            }
            for(int i = 0;i < clientArray.count;i++){
                NSDictionary *dict = clientArray[i];
                NewContactView *newContect = [[NewContactView alloc] initWithFrame:CGRectMake(0, ContactFrame.size.height * i, KSCreenW, ContactFrame.size.height)];
                newContect.nameTF.enabled = NO;
                newContect.businessTF.enabled = NO;
                newContect.phoneTF.enabled = NO;
                newContect.emailTF.enabled = NO;
                newContect.remarkTF.userInteractionEnabled = NO;
                
                newContect.nameTF.placeholder = nil;
                newContect.businessTF.placeholder = nil;
                newContect.phoneTF.placeholder = nil;
                newContect.emailTF.placeholder = nil;
                newContect.remarkTF.placehoder = nil;
                
                newContect.nameTF.text = dict[@"name"];
                newContect.businessTF.text = dict[@"position"];
                newContect.phoneTF.text = dict[@"phone"];
                newContect.emailTF.text = dict[@"email"];
                newContect.remarkTF.text = dict[@"remark"];
                //                newContect.title = dict[@"remark"];
                
                [secondView addSubview:newContect];
                if (i == clientArray.count - 1) {
                    //最后一个联系人的添加 改变一个frame
                    CGRect frame = addVie.frame;
                    frame.origin.y = newContect.maxY;
                    addVie.frame = frame;
                    
                    CGRect secondFrame = secondView.frame;
                    secondFrame.size.height = addVie.maxY;
                    secondView.frame = secondFrame;
                    
                    CGRect thirdFrame = thirdView.frame;
                    thirdFrame.origin.y = secondView.maxY;
                    thirdView.frame = thirdFrame;
                    _scrollView.contentSize = CGSizeMake(KSCreenW, thirdView.maxY + 10 + 64);
                }
            }
            
        }
        
        _companyTF.text = json[@"customer"][@"company"];
        _levelTF.text = json[@"customer"][@"levelname"];
        _fromTF.text = json[@"customer"][@"sourcename"];
        _statusTF.text = json[@"customer"][@"statusname"];
        detailDict = json[@"customer"];
        
        _addressTF.text = json[@"customer"][@"address"];
        _personTF.text = json[@"customer"][@"creatername"];
        _principalTF.text = json[@"customer"][@"uidname"];
        _creTimeTF.text = json[@"customer"][@"addtime"];
        _lastTimeTF.text = json[@"customer"][@"updatetime"];
        
    } fail:^(NSError *error) {
        NSLog(@"%@",error);
        [self.view makeToast:error.localizedDescription];
    }];
    
}
//下属客户-相关拜访
- (void)requestHistoryData{
    
    [SVProgressHUD show];
    NSNumber *cidNum =[NSNumber numberWithInt:_cID];
    
    NSNumber *pageNum1 = [NSNumber numberWithInt:pageNum];
    NSNumber *rowsNum = [NSNumber numberWithInt:20];
    NSDictionary * dic =@{@"token":TOKEN,@"uid":@(UID),@"cid":cidNum,@"page":pageNum1,@"rows":rowsNum};
    [DataTool postWithUrl:HISTORY_CLIENT_URL parameters:dic success:^(id data) {
        NSDictionary *jsonDic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        [SVProgressHUD dismiss];
        if ([jsonDic[@"code"]integerValue] == 200) {
            [DataTool showMessage:jsonDic[@"message"] view:self];
        }
        NSLog(@"%@-----+++++++",jsonDic);
        NSMutableArray *array = jsonDic[@"visitlist"];
        for (int i= 0; i<array.count; i++) {
            ClientModel *client = [[ClientModel alloc]init];
            id dd = [DataTool changeType:array[i]];
            [client setValuesForKeysWithDictionary:dd];
            [_visitArray addObject:client];
        }
        
        [_visitTableView reloadData];
        [_visitTableView.mj_header endRefreshing];
        if ([jsonDic[@"visitcount"] integerValue] == _visitArray.count) {
            [_visitTableView.mj_footer endRefreshingWithNoMoreData];
        }else{
            [_visitTableView.mj_footer endRefreshing];
        }
        
    } fail:^(NSError *error) {
        NSLog(@"%@sdsdsdsewerr",error);
        [SVProgressHUD dismiss];
        [self.view makeToast:error.localizedDescription];
        [_visitTableView.mj_header endRefreshing];
        [_visitTableView.mj_footer endRefreshing];
    }];
}

@end
